package com.apexsoft.margin.account.management.persistent.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.apexsoft.margin.account.management.domain.excel.model.FirstChainDataDomain;
import com.apexsoft.margin.account.management.persistent.mapper.FirstChainMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 融券锁券录入维护（批量）
 *
 * 上传Excel时 easyExcel的监听器
 */
public class FirstChainListener extends AnalysisEventListener<FirstChainDataDomain> {
    private static final Logger LOGGER  = LoggerFactory.getLogger(FirstChainListener.class) ;
    private static final int BATCH_COUNT = 500;

    private String fileCode;
    List<FirstChainDataDomain> list = new ArrayList<FirstChainDataDomain>();

    public static int getBatchCount() {
        return BATCH_COUNT;
    }

    public String getFileCode() {
        return fileCode;
    }

    public void setFileCode(String fileCode) {
        this.fileCode = fileCode;
    }

    FirstChainMapper securitiesMapper;
    /**
     * EasyExcel 中拒绝使用 spring 的注解，所以使用构造函数完成 变量的初始化。
     * @param
     */
    public FirstChainListener(String fileCode, FirstChainMapper mapper) {
        this.fileCode = fileCode;
        this.securitiesMapper = mapper;
    }

    public FirstChainListener(){

    }

    /**
     * 每读取一批 Excel 数据，就执行一次将数据保存到数据库中
     * @param data
     * @param context
     */
    @Override
    public void invoke(FirstChainDataDomain data, AnalysisContext context) {
        try{
            list.add(data);
            if(list.size()>=BATCH_COUNT){
                saveData();
                // 存储完成清理 list
                list.clear();
            }
        }catch (Exception e){
            LOGGER.error("异常"+e.getMessage());
        }
    }

    /**
     * 读取所有的Excel数据之后就会执行这个函数
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        try{
            saveData();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 每次调用将一条数据保存到数据库中
     * @param
     */
    private void saveData(){
        securitiesMapper.batchInsert(list,fileCode);
    }
}
